//
//  CNUISearchBar.swift
//  YiZhangGui
//
//  Created by 卢逢卫 on 2024/4/1.
//

import UIKit


public class CNUISearchBar: UISearchBar{
    
    public var cn_searchBarBeginEditingBlock: ((String) -> Void)?
    public var cn_searchBarSearchClickBlock: ((String) -> Void)?
    public var cn_searchBarIfCanEdit: Bool = true
    
    var overlayView:UIView?
    
    
//    func addTapGesture(completion: @escaping () -> Void) {
//            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
//            tapGesture.numberOfTapsRequired = 1
//            tapGesture.numberOfTouchesRequired = 1
//            addGestureRecognizer(tapGesture)
//        tapGesture.addTarget(completion, action: <#Selector#>)
//            isUserInteractionEnabled = true
//        }
//
//        @objc private func handleTap(sender: UITapGestureRecognizer) {
//            sender.addTarget(self, action: <#Selector#>)
//        }
    
    
    override init(frame: CGRect) {
            super.init(frame: frame)
            delegate = self
            self.searchBarStyle = .minimal
//        self.layer.cornerRadius = 10
//        self.layer.masksToBounds = true
        let img = UIImage.image(with: UIColor.clear, size: CGSize(width: 100, height: 40))
        self.setSearchFieldBackgroundImage(img, for: .normal)
       
       
            
                
        if #available(iOS 13.0, *) {
            self.searchTextField.subviews[0].backgroundColor = .clear
            
        } else {
            // Fallback on earlier versions
        }
       
        }
        
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            delegate = self
            
            self.searchBarStyle = .minimal
           
        }
    
//    public func cn_setSearchBarRightButton(title: String, color: UIColor) {
//        // 设置右侧按钮样式
//        // 创建右侧按钮样式
//                let rightButton = UIButton(type: .system)
//                rightButton.setTitle(title, for: .normal)
//                rightButton.setTitleColor(color, for: .normal)
//                rightButton.addTarget(self, action: #selector(rightButtonTapped), for: .touchUpInside)
//                rightButton.sizeToFit()
//
//                // 将按钮添加到搜索栏的右侧视图
//                if let textField = self.value(forKey: "searchField") as? UITextField {
//                    textField.rightView = rightButton
//                    textField.rightViewMode = .always
//                }
//    }
    
    @objc private func rightButtonTapped() {
            // 右侧按钮点击事件
//            endEditing(true) // 隐藏键盘
        
            self.resignFirstResponder()
        }
    
    public convenience init(backgroundColor: UIColor? = .clear, backgroundImage: String? = nil, leftImage: String? = nil, placeholderText: String? = nil, placeholderColor: UIColor? = nil, placeholderFont: UIFont? = nil, inputFont: UIFont? = nil, inputTextColor: UIColor? = nil, textAlignment: NSTextAlignment = .left, radius: CGFloat? = nil, borderWidth: CGFloat? = nil, borderColor: UIColor? = nil, tfHeight: CGFloat? = nil, cursorColor: UIColor? = nil, iconPosition: UIOffset? = nil, textPosition: UIOffset? = nil) {
        self.init()
        if let backgroundColor = backgroundColor {
            self.backgroundColor = backgroundColor
        }
        if let backgroundImage = backgroundImage {
            self.backgroundImage = UIImage(named: backgroundImage)
        }
        if let leftImage = leftImage {
            self.setImage(UIImage(named: leftImage), for: .search, state: .normal)
        }
        if let placeholderText = placeholderText {
            self.placeholder = placeholderText
        }
        if let placeholderColor = placeholderColor {
            self.setPlaceholderTextColor(placeholderColor)
        }
        if let placeholderFont = placeholderFont {
            self.setPlaceholderFont(placeholderFont)
        }
        if let inputFont = inputFont {
            self.setTextFont(inputFont)
        }
        if let inputTextColor = inputTextColor {
            self.setTextColor(inputTextColor)
        }
//        self.textAlignment = textAlignment
        if let radius = radius {
            self.setCornerRadius(radius)
        }
        if let borderWidth = borderWidth {
            self.setBorderWidth(borderWidth)
        }
        if let borderColor = borderColor {
            self.setBorderColor(borderColor)
        }
        if let tfHeight = tfHeight {
            self.setSearchTextFieldHeight(tfHeight)
        }
        if let cursorColor = cursorColor {
            self.setCursorColor(cursorColor)
        }
//        if let iconPosition = iconPosition {
//            self.setIconPositionAdjustment(iconPosition, for: .search)
//        }
        if let textPosition = textPosition {
            self.setPositionAdjustment(textPosition, for: .search)
        }
    }
    
    public override func layoutSubviews() {
            super.layoutSubviews()
            
            // 设置背景圆角
            let cornerRadius: CGFloat = bounds.height / 2.0
            self.layer.cornerRadius = cornerRadius
            self.clipsToBounds = true
        if !self.cn_searchBarIfCanEdit {
            overlayView = UIView(frame: self.bounds)
            overlayView!.backgroundColor = .clear
            self.addSubview(overlayView!)
        }
            
        
            
        }
    
}

extension UIImage {
    static func image(with color: UIColor, size: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }
        
        defer {
            UIGraphicsEndImageContext()
        }
        
        context.setFillColor(color.cgColor)
        context.fill(CGRect(origin: .zero, size: size))
        
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

extension CNUISearchBar: UISearchBarDelegate {
    
    public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        
        self.showsCancelButton = true
        return cn_searchBarIfCanEdit
    }
    
    public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        if let text = searchBar.text {
            cn_searchBarBeginEditingBlock?(text)
        }
    }
    
    public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
        return true
    }
    
    public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        
    }
    
    public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchBar.text == "" {
            cn_searchBarBeginEditingBlock?("")
        }
    }
    
    public func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        return true
    }
    
    public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.showsCancelButton = false
        self.resignFirstResponder()
        
    }
    
    public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if let text = searchBar.text {
            cn_searchBarSearchClickBlock?(text)
//            self.showsCancelButton = false
            self.resignFirstResponder()
        }
    }
    
    public func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
        
    }
    
    public func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) {
        
    }
    
    public func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
        
    }
    
    // Helper methods
    
    private func setPlaceholderTextColor(_ color: UIColor) {
        let textField = self.value(forKey: "searchField") as? UITextField
        textField?.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: color])
        
//        if let searchField = self.value(forKey: "searchField") as? UITextField {
//            if let backgroundView = searchField.subviews.first {
//                // 设置背景色
//                backgroundView.backgroundColor = UIColor.red
//            }
//        }
        
    }
    
    private func setPlaceholderFont(_ font: UIFont) {
        let textField = self.value(forKey: "searchField") as? UITextField
        textField?.font = font
        
    }
    
    private func setTextFont(_ font:UIFont) {
        let textField = self.value(forKey: "searchField") as? UITextField
        textField?.font = font
    }
    
    private func setTextColor(_ color: UIColor) {
        let textField = self.value(forKey: "searchField") as? UITextField
        textField?.textColor = color
    }
    
    private func setCornerRadius(_ radius: CGFloat) {
        let textField = self.value(forKey: "searchField") as? UITextField
        textField?.layer.cornerRadius = radius
        textField?.layer.masksToBounds = true
    }
    
    private func setBorderWidth(_ width: CGFloat) {
        let textField = self.value(forKey: "searchField") as? UITextField
        textField?.layer.borderWidth = width
    }
    
    private func setBorderColor(_ color: UIColor) {
        let textField = self.value(forKey: "searchField") as? UITextField
        textField?.layer.borderColor = color.cgColor
    }
    
    private func setSearchTextFieldHeight(_ height: CGFloat) {
        let textField = self.value(forKey: "searchField") as? UITextField
        textField?.heightAnchor.constraint(equalToConstant: height).isActive = true
    }
    
    private func setCursorColor(_ color: UIColor) {
        let textField = self.value(forKey: "searchField") as? UITextField
        textField?.tintColor = color
    }
}



